package com.baidu.mpks.filter;


import com.baidu.mpks.user.domain.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginFilter extends AccessControlFilter {
    private static final Logger log = LoggerFactory.getLogger(LoginFilter.class);
    private String redirectUrl;

    public LoginFilter() {
    }

    public void setRedirectUrl(String redirectUrl) {
        this.redirectUrl = redirectUrl;
    }

    public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        HttpServletRequest req = (HttpServletRequest)request;
        return super.onPreHandle(request, response, mappedValue);
    }

    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        if (user != null) {
            String api = ((HttpServletRequest)request).getRequestURI();
            return true;
        } else if (this.pathsMatch("/login", request)) {
            return true;
        } else {
            HttpServletResponse resp = (HttpServletResponse)response;
            resp.setStatus(401);
            log.info("===Customer redirectURL===:{}", this.redirectUrl);
            resp.setHeader("redirectURL", this.redirectUrl);
            return false;
        }
    }

    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        return false;
    }

    public void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        request.setAttribute("time", System.currentTimeMillis());
        super.doFilterInternal(request, response, chain);
        long time = (Long)request.getAttribute("time");
        String api = ((HttpServletRequest)request).getRequestURI();
        if ("/login".equals(api)) {
            try {
                User var7 = (User)SecurityUtils.getSubject().getPrincipal();
            } catch (Exception var8) {
                log.error("");
            }
        }

    }
}